import React, { useImperativeHandle, forwardRef } from 'react'
import { Form, AutoComplete, Input, message } from 'antd'
import { emailPattern } from '@js/config'
import { awaitWrap } from '@js/tool'
import { $get } from '@js/authRequest'
const { Item } = Form

// 获取电子送达地址内容
async function getElectronicContentRequest (caseid, type, addressid) {
  const res = await $get('/api/xapc/deliver/getDigitalDeliverContent', {
    caseid,
    topic_type: type,
    addressid
  })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

// 获取送达内容
async function getElectronicContent (pState, addressid, formRef) {
  const [e, d] = await awaitWrap(getElectronicContentRequest(pState.caseDetail.id, pState.toType, addressid))
  if (e) {
    return message.error(e.message)
  }
  const documentid = (d.documents || []).map(li => li.id)
  delete d.documents
  d.documentid = documentid
  formRef.current.setFieldsValue(d)
}

// 修改地址
function changeAddress (formRef, o, pState) {
  if (pState.toType === '电子送达') {
    getElectronicContent(pState, o.id, formRef)
  }
  setTimeout(() => {
    formRef.current.setFieldsValue({
      contract: o.contract || undefined,
      addressid: o.id || undefined,
      type: o.type || undefined,
      zip_code: o.zip_code || undefined,
      structure: o.structure || undefined,
      mobile: o.mobile || undefined,
      tel: o.tel || undefined,
      tel_office: o.tel_office || undefined,
      address: o.address || undefined,
      email: o.email || undefined
    })
  }, 0)
}

function Main ({ formRef, pState }, ref) {
  useImperativeHandle(ref, () => ({
    changeAddress
  }))
  return (
    <>
      <Item name='mobile' label='移动电话' rules={[{ required: true, message: '移动电话不能为空' }, { pattern: /^1\d{10}(,1\d{10})*$/g, message: '移动电话格式不正确，多个移动电话请以英文逗号隔开' }]}>
        <AutoComplete options={pState.currentElectronicAddressList} onSelect={(value, option) => changeAddress(formRef, option, pState)}>
          <Input placeholder='请输入移动电话' />
        </AutoComplete>
      </Item>
      <Item name='email' label='邮箱' rules={[{ pattern: emailPattern, message: '电子邮箱格式不正确，多个电子邮箱请以英文逗号隔开' }]}>
        <Input placeholder='请输入邮箱' />
      </Item>
    </>
  )
}

export default forwardRef(Main)
